package com.duqc.zk;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.nio.charset.StandardCharsets;

/**
 * @ClassName ZooKeeperTest
 * @Description TODO
 * @Author duqc
 * @Date 2021/5/13
 **/
@Slf4j
public class ZooKeeperTest {

    /**
     * 连接地址及端口号
     */
    private static final String SERVER_HOST = "127.0.0.1:2181";

    /**
     * 会话超时时间
     */
    public static final int SESSION_TIME_OUT = 2000;

    public static void main(String[] args) throws Exception {
        ZooKeeper zooKeeper = new ZooKeeper(SERVER_HOST, SESSION_TIME_OUT, watchedEvent -> {
            //获取事件的状态
            Watcher.Event.KeeperState state = watchedEvent.getState();
            //判断是否是连接操作
            if (Watcher.Event.KeeperState.SyncConnected == state) {
                Watcher.Event.EventType type = watchedEvent.getType();
                if (Watcher.Event.EventType.None == type) {
                    log.info("zk客户端已连接...");
                }
            }
        });
        //新增
//        zooKeeper.create("/java", "Hello World".getBytes(StandardCharsets.UTF_8),
//                ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
//        log.info("新增ZNODE成功");

        //查询
//        Stat stat = new Stat();
//        byte[] data = zooKeeper.getData("/java", false, stat);
//        log.info("ZNODE的数据data:" + new String(data));
//        log.info("获取到dataVersion版本号:" + stat.getVersion());
//
//        //更新
//        zooKeeper.setData("/java", "fly!!!".getBytes(StandardCharsets.UTF_8),stat.getVersion());
//        byte[] data1 = zooKeeper.getData("/java", false, stat);
//        log.info("ZNODE的数据data:" + new String(data1));
//        log.info("获取到dataVersion版本号:" + stat.getVersion());
//
//        //删除
//        zooKeeper.delete("/java",stat.getVersion());

        //注册监听器
//        zooKeeper.exists("/java",new MyWatcher());
//        zooKeeper.setData("/java","fly".getBytes(StandardCharsets.UTF_8),-1);

//        //一次性
//        zooKeeper.exists("/java", input -> {
//            log.info("我是exists()方法的监听器");
//        });
//        //对ZNode进行更新数据的操作，触发监听器
//        zooKeeper.setData("/java", "fly".getBytes(), -1);
//        //企图第二次触发监听器
//        zooKeeper.setData("/java", "spring".getBytes(), -1);

        //串行执行
        zooKeeper.exists("/java", watchedEvent -> {
            log.info("我是exist()方法的监听器");
        });
        Stat stat = new Stat();
        zooKeeper.getData("/java", watchedEvent -> {
            log.info("我是getData()方法的监听器");
        }, stat);
        //对ZNode进行更新数据的操作，触发监听器
        zooKeeper.setData("/java", "fly".getBytes(), stat.getVersion());
        zooKeeper.close();
    }
}
